import { Component, OnInit, ViewChild } from '@angular/core';
import { STPage, STComponent, STColumn, STChange } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-system-user-role',
  templateUrl: './user-role.component.html'
})
export class UserRoleComponent implements OnInit {
  record: any = {};
  params: any = {};
  userRoleList: any[] = [];
  page: any = {
    records: [],
    current: 1,
    total: 0,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  searchSchema: SFSchema = {
    properties: {
      name: {
        type: 'string',
        title: '角色名称',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      code: {
        type: 'string',
        title: '角色代码',
        ui: {
          acl: { ability: ['query'] }
        }
      }
    }
  };
  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: '角色名称', index: 'name' },
    { title: '角色代码', index: 'code' },
    { title: '描述', index: 'description' },
    {
      title: '操作',
      buttons: [
        {
          text: '选择',
          icon: 'check',
          click: record => {
            this.setUserRole(record);
          },
          acl: { ability: ['edit'] }
        }
      ]
    }
  ];

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    private modalService: NzModalService,
    public http: _HttpClient
  ) {}

  ngOnInit(): void {
    // this.query();
    // this.queryCandidate(null);
  }

  change(e: STChange) {
    if (e.type === 'pi' || e.type === 'ps') {
      this.params.size = e.ps;
      this.params.current = e.pi;
      this.queryCandidate(null);
    }
  }

  query() {
    this.http.get(`${Api.BaseRoleApi}user/${this.record.id}`).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        this.userRoleList = res.data || [];
      }
    });
  }

  queryCandidate(event: any) {
    const current: number = this.params.current || 1;
    const size: number = this.params.size || 10;
    let searchParams: any = { username: this.record.username };
    if (event) {
      if (event.name) {
        searchParams.name = event.name;
      }
      if (event.code) {
        searchParams.code = event.code;
      }
    }
    this.http.get(`${Api.BaseRoleApi}page/candidate/${current}/${size}`, searchParams).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.page = res.data;
      }
    });
  }

  setUserRole(value: any) {
    if (this.userRoleList) {
      const exists: any = this.userRoleList.filter(item => item.id === value.id);
      if (exists && exists.length > 0) {
        this.msgSrv.error('该角色已配置给用户,请勿重复配置');
        return;
      }
    }
    this.modalService.confirm({
      nzTitle: '确定配置吗?',
      nzContent: '如果您确定要配置请点击确定按钮，否则点取消',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        const url = `${Api.BaseRoleApi}user/${this.record.id}/${value.id}`;
        this.http.post(url).subscribe((res: any) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.query();
              this.msgSrv.success('配置成功');
            } else {
              this.msgSrv.warning(res.message);
            }
          } else {
            this.msgSrv.error('配置失败，未知错误');
          }
        });
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  deleteUserRole(value: any) {
    this.modalService.confirm({
      nzTitle: '确定删除吗?',
      nzContent: '<b style="color: red;">如果您确定要删除请点击确定按钮，否则点取消</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        const url = `${Api.BaseRoleApi}user/${this.record.id}/${value.id}`;
        this.http.delete(url).subscribe((res: any) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.query();
              this.msgSrv.success('删除成功');
            } else {
              this.msgSrv.warning(res.message);
            }
          } else {
            this.msgSrv.error('删除失败，未知错误');
          }
        });
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  close() {
    this.modal.destroy();
  }
}
